<?php
// +----------------------------------------------------------------------
// | 奇乐中介担保交易系统 免费版 2019
// +----------------------------------------------------------------------
// | 官方网址：http://www.qilecms.com   
// +----------------------------------------------------------------------
// | 产品文档：http://www.qilecms.com/doc
// +----------------------------------------------------------------------
// | 开发作者: 奇乐CMS
// +----------------------------------------------------------------------
// | 版权说明：这不是一个自由软件！本产品仅限个人使用，但请务必保留底部版权，以免产生不必要的纠纷,
// | 您只能在不用于商业目的的前提下对程序代码进行修改和使用，
// | 任何企业和个人不允许对程序代码以任何形式任何目的再发布。
// +----------------------------------------------------------------------
namespace app\admin\controller;
use think\controller;
use think\Db;
class Message extends Base
{
	public function index(){
      $alias = '';        //需要别名时写别名，不需要的时候留空 
      $defaultOrder = 'create_time desc';  //默认排序
//消息类型 
          $param = $this->request->param();
           if($param['type'] >= '0' ){
             $type = $param['type'];
              $defaultWhere ='type = '.$param['type'];  //默认wher
        }else{
             $type  = ''; 
             $defaultWhere = '';
        }

     $this->assign('type',$type);

    //接收搜索表单数据
      $SearchFormData = $this->getSearchFormData($defaultWhere,$defaultOrder);
      $where   = $SearchFormData['where'];
      $order   = $SearchFormData['order'];
      $pageNum = $SearchFormData['pageNum'];

//组建关键词数据
     $keywordsData  =[
                  [
                  'field'   =>'title', //字段名
                  'name'    =>'消息标题', //文本显示名称
                  'alias'   => $alias,  //字段对应的别名
                  ],
                  [
                  'field'   =>'from_username',
                  'name'    =>'发信人',
                  'alias'   => $alias,
                  ],
                  [
                  'field'   =>'to_username',
                  'name'    =>'收信人',
                  'alias'   => $alias,
                  ]
     ];
//组建日期筛选   
       $dateData = [
                  [
                  'title'        =>'创建时间',  //标签显示名称
                  'field'        =>'create_time', //筛选字段
                  'start_name'   =>'开始时间', //开始时间
                  'end_name'     =>'结束时间', //结束时间
                  'alias'        => $alias,  //字段别名
                  ],

              ];
//单个字段筛选
    $customSingleField =[
                            [
                             'name'=>'状态',
                             'field' => 'is_read', 
                             'data'  => [ 0 =>'未读',1=>'已读'],
                             'alias'=>$alias,
                            ]
                       ]; 
// 组件字段组筛选
    $groupData = [
               
              ];
     $orderData   = [
               
               ];  

     $this->assign('keywordsData',$keywordsData);
     $this->assign('customSingleField',$customSingleField);
     $this->assign('groupData',$groupData);
     $this->assign('dateData',$dateData);
     $this->assign('orderData',$orderData);


     $lists = DB::name('message')->where($where)->order($order)->paginate($pageNum);
     $list = $lists->toArray()['data'];

     foreach($list as $k=>$v){
          $m['uid'] = $v['from_uid'];
          $fromUser = model('user')->infoData($m);
          $list[$k]['from_username'] = $fromUser['username'];
          $map2['uid'] = $v['to_uid'];
          $toUser = model('user')->infoData($map2);
          $list[$k]['to_username'] = $toUser['username'];

     }
     $page = $lists->render();
     $this->assign('page', $page);
     $this->assign('list', $list);

     return $this->fetch();
	}
//增加
  public function add(){
    $param = $this->request->param(); 
    if($this->request->isPost()){   

        //验证
        $rule =[
          'title'=>'require',
          'content'=>'require',
        ];
        $msg= [
         'title.require' =>'消息标题不能为空',
         'content.require' =>'消息内容不能为空',
        ];
         $error = $this->checkSubmit($param,$rule,$msg);  
       if($error){
              return error_json($error);
         }
         //表单数据
          $data['title'] = $param['title'];
          $data['type'] = $param['type'];
          $data['content'] = $param['content'];
		      $data['create_time'] = time();
          $data['from_uid'] = $param['type'];
          if($param['type'] ==0){
          	//群发通知
          	  $data['remark'] = '系统消息';
              //通知用户组识别
              if(is_array($param['level_id'])){
                   $data['level_id'] = implode(',',$param['level_id']);
                   $where = "level_id IN (".$data['level_id'].")";
                   $UserLevel = model('UserLevel')->where($where)->select();
                   $arr =[];
                   foreach($UserLevel as $v){
                       array_push($arr,$v['level_name']); 
                   }
                   $userGroupName = implode(',',$arr);
              }else{
                   $data['level_id']  = $param['level_id'];
                   $where['level_id'] = $data['level_id'];
                   $UserLevel = model('UserLevel')->where($where)->find();
                   $userGroupName= $UserLevel['level_name'];
                   
              }
               $data['remark'] = ''.$userGroupName.'';
               model('message')->addData($data);
			         return success_json('通知群发成功'); 
          }else if($param['type'] ==1){
          	//发私信
            
              $arrs = explode("\n",$param['to_username']);
              $arr = [];
              foreach($arrs as $k=>$v){
                 $where['username'] = trim($v);
                 $res = model('user')->infoData($where);
                 if(empty($res)){
                  return error_json('用户名'.trim($v).'不存在');
                 }
                 $arr[] = trim($v);
              }

              $data['from_uid'] = 0;   
              $map[] = ['username','IN',$arr];
              $map[] = ['status','=',1];
              $users = model('user')->listData($map);

              foreach($users as $user){
              	  $data['to_uid'] = $user['uid'];
                  model('message')->addData($data);
			            
              }         
               return success_json('私信发送成功'); 
          }

        


 
   }else{
   	     $UserLevel = model('UserLevel')->getUserLevelList();
   	     $this->assign('UserLevel',$UserLevel);
         return $this->fetch();
   }      
  }
  public function edit(){
    $param = $this->request->param();
    if($this->request->isPost()){

        //验证
        $rule =[
          'title'=>'require',
          'content'=>'require',
        ];
        $msg= [
         'title.require' =>'消息标题不能为空',
         'content.require' =>'消息标题不能为空',
        ];
         $error = $this->checkSubmit($param,$rule,$msg);  
       if($error){
              return error_json($error);
         }
    
        //表单数据       
          $data['title'] = $param['title'];
          $data['level_id'] = $param['level_id'];
          $data['type'] = $param['type'];
          $data['content'] = $param['content'];
          $data['status'] = !empty($param['status'])?1:0;
          $where['id'] = $param['id'];
          $res = model('message')->editData($data,$where);
          return success_json('编辑成功'); 
    }else{
         $rule = model('message')->getRuleInfoById($param['id']);
         $this->assign('rule',$rule);
         return $this->fetch();


    }  
  }
  public function content(){
    $param =$this->request->param();

    if(!empty($param['mid'])){
      $mid =intval($param['mid']);
      $map[]= ['mid','=',$mid];
      $message = model('message')->infoData($map);
 
      $this->assign('message',$message);
     return  $this->fetch();
    }
  }
  public function del(){
      $param = $this->request->param();
     if(!$param['mid']){  return error_json('请求参数错误');    }

     $res= $this->delData('message',"mid");
       if($res){
         return success_json('删除成功');
       }else{
         return error_json($res);
       }
    }
      

}